<template>
  <div>
    <el-dialog
      title="扣款申诉"
      :visible.sync="isShow"
      center
      width="40%"
      append-to-body
      :before-close="handleClose">
      <!-- <div v-if="noReason">
        <div>您本月有一次无理由申诉机会，是否确认无理由申诉？</div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submit('ruleForm')">确认申诉</el-button>
        </div>
      </div>
      <div v-else> -->
        <el-form :model="form" :rules="rules" ref="ruleForm" label-position='top' label-width="100px">
          <el-form-item label="申诉原因：" prop="reason">
            <el-input
              type="textarea"
              v-model="form.reason"
              :show-word-limit="true"
              :maxlength="500"
              :rows="4"></el-input>
          </el-form-item>

          <el-upload 
            class="upload-demo" 
            ref="upload" 
            :auto-upload="false" 
            :on-change="handleChange" 
            action=''
            :file-list="fileList" 
            :http-request="uploadSectionFile"
            :on-remove="handleRemove" 
            multiple 
            :limit="5">
            <!-- <div slot="tip" class="el-upload__tip">文件不要超过100MB</div> -->
            <el-button  slot="trigger" size="medium" type="primary" class='mt20'>选择申诉凭证</el-button>
          </el-upload>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submit('ruleForm')">
            申 诉
            <!-- 您可以在结算7天内发起申诉 -->
          </el-button>
          <!-- <el-button v-if="noReason" type="primary" @click="appeal_out">
            无理由申诉
            <el-popover placement="bottom" title="无理由申诉" width="200" trigger="hover">
              <span>您可以在结算7天内发起申诉；</span><br />
              <span>高级代理人每月有一次无理由申诉机会</span>
              <i class="el-icon-info orange ml10" slot="reference"></i>
            </el-popover>
          </el-button> -->
        </div>
      <!-- </div> -->
      
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data () {
    return {
      noReason: false,
      isShow: false,
      form: {
        reason: '',
      },
      type: null,
      rules: {
        reason: [
          { required: true, message: '请输入申诉原因', trigger: 'change' }
        ]
      },
      baseUrl: global.baseurl,
      fileList: [],
      fileListV: [],
      appeal_id: null,
    }
  },
  created () {
    if(this.$store.state.user.grade == 3){
      this.noReason = true
    }
  },
  methods: {
    cancel(){
      this.noReason = false
    },
    show (data) {
      this.appeal_id = data.id
      this.isShow = true
    },

    submit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitPost()
          // this.isShow = false
        } else {
          return false
        }
      });
    },
    submitPost () {
      let list = document.getElementsByClassName(
        "el-upload-list__item is-ready"
      );
      if (list.length == 0) {
        this.$message({
          type: "warning",
          message: "请选择需要发送的申诉凭证！"
        });
        return;
      }
      // FormData 对象
      var form = new FormData();
      // 文件对象
      for (let i in this.fileListV) {
        form.append(i==0?"file":("file"+(i*1+1)), this.fileListV[i].raw);
      }
      form.append('appeal_id', this.appeal_id)
      form.append('reason', this.form.reason)
      form.append('type', "App\\Models\\Deduction")
      axios({
        method: "post",
        url: this.baseUrl + "/api/appeals",
        data: form,
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: "Bearer " + this.$store.state.token
        }
      }).then( res => {
        if (res.data.code == 200) {
          this.$message({
            type: 'success',
            message: '申诉申请成功，请耐心等待结果。'
          })
          this.$emit('refresh')
          this.isShow = false
        } else {
          this.$message({
            type: 'error',
            message: res.data.message
          })
        }
      }).catch(e => {
        console.log(e)
      })
    },
    // 无理由申诉
    appeal_out(){
      let params = {
        appeal_id:this.appeal_id,
        type: 'App\\Models\\Deduction',
        exempt_review:1
      }
      this.$axios
      .post("/api/appeals",params)
      .then(res => {
        if (res.data.code == 200) {
          this.$alert('申诉申请成功', "提示", {
            confirmButtonText: "确定",
            center: true,
            type: "success",
            callback: action => {}
          });
        }else{
          this.$alert(res.data.message, "提示", {
            confirmButtonText: "确定",
            center: true,
            type: "success",
            callback: action => {}
          });
        }
      })
      .catch(err => {
        this.$message.error(err);
      });
    },
    handleClose () {
      this.isShow = false
      this.$refs['ruleForm'].resetFields()
    },
    handleChange(file, fileList) {
      let tempList = [];
      for(let i = 0;i<fileList.length;i ++){
        let canUpload = true;//是否可以上传
        let that = this;
        //验证文件类型
        let fileName = fileList[i].name;
        let pos = fileName.lastIndexOf(".");
				let lastName = fileName.substring(pos, fileName.length);
        // let type = file.name.substring(fileList[i].name.lastIndexOf('.') + 1);
        // if (!/jpg|jpeg|png|gif/i.test(lastName)) {
        if (
						lastName.toLowerCase() !== ".jpg" &&
						lastName.toLowerCase() !== ".jpeg" &&
						lastName.toLowerCase() !== ".png"
					) {
          that.$message.error("文件格式只能是jpg/jpeg/png",);
          canUpload = false;
        }
        if(canUpload){
          tempList.push(fileList[i]);
        }
      }
      this.fileListV.splice(0,this.fileListV.length,...tempList);
      fileList.splice(0,fileList.length,...tempList);
      return ;
    },
    handleRemove(file, fileList) {
      this.fileListV = fileList;
    },
    uploadSectionFile(){
    },
  }
}
</script>

<style lang='less' type='text/css'>
  .el-form {
    .prompt {
      font-size: 12px;
      margin: 0 0 10px 100px ;
    }
  }
</style>
